import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
/*
public class Main {

    public static void main(String[] arg) throws Exception {
	//创建http服务器，绑定本地8001端口
        HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);
	//创建上下文监听，拦截包含/test的请求
        server.createContext("/hello", new TestHandler());
	server.createContext("/version",new TestHandler());
	//启动服务
        server.start();
    }

    static  class TestHandler implements HttpHandler{
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("addr:" + exchange.getRemoteAddress() + 
		"; protocol: " + exchange.getProtocol() +
		"; method: " + exchange.getRequestMethod() +
		"; URI: " + exchange.getRequestURI());
	    
	    String response = "hello world";
            exchange.sendResponseHeaders(200, 0);
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}
*/

public class Main {
	public static void main(String[] args) throws Exception {
		//创建http服务器，绑定本地8001端口
		HttpServer httpServer = HttpServer.create(new InetSocketAddress(8001),0);

		//创建上下文监听，"/" 表示匹配所有URI请求
		httpServer.createContext("/hello",new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				System.out.println("addr:" + httpExchange.getRemoteAddress() +	//客户端IP地址 
                  			"; protocol: " + httpExchange.getProtocol() +		//请求协议：HTTP/1.1
                  			"; method: " + httpExchange.getRequestMethod() +	//请求方法：GET，POST
 		                	"; URI: " + httpExchange.getRequestURI());		//请求URI

				//获取请求头
				String userAgent = httpExchange.getRequestHeaders().getFirst("User-Agent");
				System.out.println("User-Agent:" + userAgent);
				
				//响应内容
				byte[] respContents = "Hello World".getBytes("UTF-8");
		
				//设置响应头
				httpExchange.getResponseHeaders().add("Content-Type","text/html; charset=UTF-8");
				//设置响应code和内容长度
				httpExchange.sendResponseHeaders(200,respContents.length);
				//设置响应内容
				httpExchange.getResponseBody().write(respContents);
				//关闭处理器
				httpExchange.close();
			}
		});

		//创建上下文监听，处理URI以 "/version" 为开头的请求
		httpServer.createContext("/version",new HttpHandler() {
			@Override
			public void handle(HttpExchange httpExchange) throws IOException {
				//响应内容
				byte[] respContents = "{\"version\":\"0.0.1\"}".getBytes("UTF-8");
				
				httpExchange.getResponseHeaders().add("Content-Type","text/heml; charset=UTF-8");
				httpExchange.sendResponseHeaders(200,respContents.length);

				httpExchange.getResponseBody().write(respContents);
				httpExchange.close();
			}
		});

			//启动服务
			httpServer.start();
	}
}
